package foo.websystem.bo;

import java.util.LinkedHashMap;
import java.util.List;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import foo.base.BaseBO;
import foo.websystem.action.Consts;
import foo.websystem.dao.UserDAO;
import foo.websystem.vo.SessionUser;

@Service
public class SystemBO extends BaseBO {

	@Autowired
	private UserDAO userDAO;

	public SessionUser getUser(HttpSession session) {
		return (SessionUser) session.getAttribute(Consts.USER);
	}

	public LinkedHashMap<String, String> getAllUserMap() {
		List<SessionUser> users = userDAO.getAllUser();
		LinkedHashMap<String, String> userMap = new LinkedHashMap<String, String>();
		for (SessionUser user : users) {
			userMap.put(user.getUserId(), user.getUserName());
		}
		return userMap;
	}

	public void login(HttpSession session, String userId, String password)
			throws Exception {
		try {
			SessionUser user = (SessionUser) session.getAttribute(Consts.USER);
			// 先從Session中尋user資訊，如果找到就直接返回
			if (user != null) {
				return;
			} else {
				user = userDAO.getUser(userId);
			}
			if (user != null) {
				boolean correctPassword = user.getPassword().equals(password);
				if (!correctPassword) {
					throw new LoginException("密碼錯了");
				} else {
					session.setAttribute(Consts.USER, user);
				}
			} else {// 資料庫找不到user資訊
				throw new LoginException("沒這個人");
			}

		} catch (Exception e) {
			logger.error("登入失敗:", e);
			throw e;
		}
	}

}
